﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

using DragDraw.Util;
using DragDraw.UserService;

namespace DragDraw.Tool
{
    public partial class PhotoRiver : UserControl, IPhotoPlayer
    {
        public List<Photo> Photos { get; set; }
        internal WidgetServiceProxy ServiceProxy;
        internal WidgetSpaceProxy SpaceProxy;
        private List<PhotoGrid> m_grids = new List<PhotoGrid>();
        private PhotoBoard m_board;
        private Storyboard m_riverSB;
        private Storyboard m_genSB;
        private DateTime m_lastUpdate;
        private int m_curIndex = 0;
        public const int PHOTO_ON_SCREEN = 5;
        public PhotoRiver()
        {
            InitializeComponent();
            m_board = new PhotoBoard();
            Photos = new List<Photo>();

            m_riverSB = new Storyboard();
            m_lastUpdate = DateTime.Now;
            m_riverSB.SetValue(FrameworkElement.NameProperty, "RiverLoop");
            this.Resources.Add("RiverLoop", m_riverSB);
            m_riverSB.Completed += new EventHandler(m_riverSB_Completed);
            
            m_genSB = new Storyboard();
            m_genSB.Duration = new Duration(TimeSpan.FromSeconds(2));
            m_genSB.SetValue(FrameworkElement.NameProperty, "GenLoop");
            this.Resources.Add("GenLoop", m_genSB);
            m_genSB.Completed += new EventHandler(m_genSB_Completed);
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            ServiceProxy = OperationManager.Instance.CreateWidgetServiceProxy(this);
            ServiceProxy.GetSessionCompleted += OnGetSession;
            ServiceProxy.SetSessionCompleted += OnSetSession;
            SpaceProxy = OperationManager.Instance.CreateWidgetSpaceProxy(this);

            ServiceProxy.GetSession("Photos");
        }

        private void OnGetSession(object sender, DragDraw.UserService.GetSessionCompletedEventArgs e)
        {
            if (string.IsNullOrEmpty(e.Result))
            {
            }
            else
            {
                try
                {
                    XmlSerializer xs = new XmlSerializer(typeof(List<Photo>));
                    XmlReader xr = XmlReader.Create(new StringReader(e.Result));

                    Photos = (List<Photo>)xs.Deserialize(xr);
                    m_curIndex = 0;
                }
                catch
                {
                    Photos.Clear();
                }
            }
            PhotoRefresh();
        }

        void m_genSB_Completed(object sender, EventArgs e)
        {
            Random rand = new Random();
            // every 2 secs, check whether less than 5 photos on screen
            if (m_grids.Count == 0) return;
            int count = 0;
            foreach (PhotoGrid g in m_grids)
            {
                if (g.PosX < Width && g.PosX >= 0)
                    count++;
            }
            if (count < PHOTO_ON_SCREEN && count < m_grids.Count)
            {
                PhotoGrid g = m_grids[m_curIndex];
                g.PosX = 0;
                g.PosY = rand.Next(0, (int)Height - 150);
                g.PosZ = rand.Next(70, 100);
                g.Show = true;
                m_curIndex = (m_curIndex + m_grids.Count + 1) % m_grids.Count;
            }
            m_genSB.Begin();
        }

        void m_riverSB_Completed(object sender, EventArgs e)
        {
            DateTime now = DateTime.Now;
            TimeSpan elapsed = now - m_lastUpdate;
            foreach (PhotoGrid g in m_grids)
            {
                g.PosX += 50.0 * elapsed.TotalSeconds * ((double)(g.PosZ)/100.0);
                //ErrorManager.Instance.ShowDebugMessage(g.PosX.ToString());
                if (g.PosX > Width - g.Width - 50.0 * 0.5)
                    g.Show = false;
            }
            m_lastUpdate = now;

            (sender as Storyboard).Begin(); // repeat storyboard
        }


        private void CreatePhotoGrids()
        {
            m_grids.Clear();
            foreach (Photo p in Photos)
            {
                PhotoGrid g = new PhotoGrid();
                g.ImageSrc = p.ImgUrl;
                m_grids.Add(g);
            }
        }

        private void PhotoRefresh()
        {
            Random rand = new Random();
            CreatePhotoGrids();
            PhotoRoot.Children.Clear();
            foreach(PhotoGrid g in m_grids)
            {
                g.PosX = Width + 100;
                g.PosY = rand.Next(0, (int)Height);
                g.PosZ = rand.Next(70, 100);
                //ErrorManager.Instance.ShowDebugMessage(g.PosY.ToString() + " " + g.PosZ.ToString());
                PhotoRoot.Children.Add(g);
            }
            m_riverSB.Begin();
            m_genSB.Begin();
        }

        private void OnSetSession(object sender, DragDraw.UserService.SetSessionCompletedEventArgs e)
        {
            if (e.Result == false)
            {
                ErrorManager.Instance.ShowLastServiceError();
            }
        }

        public void SavePhotos()
        {
            StringWriter sw = new StringWriter();
            XmlSerializer xs = new XmlSerializer(typeof(List<Photo>));
            xs.Serialize(sw, Photos);
            ServiceProxy.SetSession("Photos", sw.ToString());
            PhotoRefresh();
        }

        private void LayoutRoot_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (WidgetHelper.IsInMySpace)
            {
                m_board.Init(this);
                SpaceProxy.ShowModalDialog(m_board, "相册设置");
            }
        }
    }
}
